<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="开始" prop="startTime">
        <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择开始">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束" prop="endTime">
        <el-date-picker clearable v-model="queryParams.endTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择结束">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable v-model="queryParams.createdAt" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付状态" prop="paymentStatus">
        <el-select v-model="queryParams.paymentStatus" placeholder="请选择支付状态" clearable>
          <el-option v-for="dict in payment_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="总费用" prop="totalCost">
        <el-input v-model="queryParams.totalCost" placeholder="请输入总费用" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:order:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:order:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['system:order:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderId" />
      <el-table-column label="客户" align="center" prop="clientName" />
      <el-table-column label="会议室" align="center" prop="roomName" />
      <el-table-column label="开始" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" prop="paymentStatus">
        <template #default="scope">
          <dict-tag :options="payment_status" :value="scope.row.paymentStatus" />
        </template>
      </el-table-column>
      <el-table-column label="总费用" align="center" prop="totalCost" />
      <el-table-column label="支付时间" align="center" prop="paymentTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.paymentTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户取消时间" align="center" prop="cancellationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.cancellationTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']">删除</el-button>
          <el-button link type="primary" icon="Money" @click="handlePay(scope.row)" v-hasPermi="['system:order:pay']"
            :disabled="scope.row.paymentStatus !== 0">支付</el-button>
          <el-button link type="primary" icon="Close" @click="handleCancel(scope.row)"
            v-hasPermi="['system:order:cancel']" :disabled="scope.row.status === 2 ">
            {{ scope.row.auditStatus === 1 ? '确认取消' : '取消' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改会议室预订订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder, payOrder, cancleOrder, confirmCancelOrder } from "@/api/system/order"

const { proxy } = getCurrentInstance()
const { order_status, payment_status } = proxy.useDict('order_status', 'payment_status')

const orderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    clientId: null,
    roomId: null,
    startTime: null,
    endTime: null,
    createdAt: null,
    status: null,
    paymentStatus: null,
    totalCost: null,
    clientName: null,
    roomName: null
  },
  rules: {
    status: [
      { required: true, message: "订单状态不能为空", trigger: "change" }
    ],
    paymentStatus: [
      { required: true, message: "支付状态不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// /​**​ 查询会议室预订订单列表 */
function getList() {
  loading.value = true
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消订单按钮操作
function handleCancel(row) {
  // 如果订单已经审核通过，显示二次确认弹窗
  if (row.auditStatus === 1) {
    handleConfirmCancel(row)
    return
  }

  proxy.$confirm(
    `
    <div>
      <h4>退费规则：</h4>
      <ul style="margin: 10px 0; padding-left: 20px;">
        <li>提前72小时退全款</li>
        <li>提前48小时退75%</li>
        <li>提前24小时退25%</li>
      </ul>
      <p>是否确认取消订单？</p>
    </div>
    `,
    '取消订单确认',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确认取消',
      cancelButtonText: '返回',
      type: 'warning',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;
          cancleOrder({ orderId: row.orderId })
            .then(() => {
              proxy.$modal.msgSuccess("退订单提交成功，待审核");
              getList(); // 刷新列表
              done();
            })
            .catch(() => {
              instance.confirmButtonLoading = false;
            });
        } else {
          done();
        }
      }
    }
  ).catch(() => {
    // 用户点击了取消
  });
}

// 二次确认取消订单
function handleConfirmCancel(row) {
  proxy.$confirm(
    '该取消申请已通过审核，确认执行取消操作吗？',
    '二次确认取消订单',
    {
      confirmButtonText: '确认取消',
      cancelButtonText: '返回',
      type: 'warning',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;
          confirmCancelOrder({ orderId: row.orderId })
            .then(() => {
              proxy.$modal.msgSuccess("订单已成功取消");
              getList(); // 刷新列表
              done();
            })
            .catch(() => {
              instance.confirmButtonLoading = false;
            });
        } else {
          done();
        }
      }
    }
  ).catch(() => {
    // 用户点击了取消
  });
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    clientId: null,
    roomId: null,
    startTime: null,
    endTime: null,
    createdAt: null,
    status: null,
    paymentStatus: null,
    totalCost: null,
    expiresAt: null,
    paymentTime: null,
    cancellationTime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("orderRef")
}

// /​**​ 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

// /​**​ 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// /​**​ 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加会议室预订订单"
}

// /​**​ 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _orderId = row.orderId || ids.value
  getOrder(_orderId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改会议室预订订单"
  })
}

// /​**​ 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.orderId != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

// /​**​ 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value
  proxy.$modal.confirm('是否确认删除会议室预订订单编号为"' + _orderIds + '"的数据项？').then(function () {
    return delOrder(_orderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

// /​**​ 导出按钮操作 */
function handleExport() {
  proxy.download('system/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

// /​**​ 支付按钮操作 */
function handlePay(row) {
  proxy.$confirm(`确认要支付订单 "${row.orderId}" 吗?`, '支付确认', {
    confirmButtonText: '确认支付',
    cancelButtonText: '取消',
    type: 'warning',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true;
        payOrder({ orderId: row.orderId })
          .then(() => {
            proxy.$modal.msgSuccess("支付成功");
            getList(); // 刷新列表
            done();
          })
          .catch(() => {
            instance.confirmButtonLoading = false;
          });
      } else {
        done();
      }
    }
  }).catch(() => {
    // 用户点击了取消
  });
}

getList()
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>